package com.alex.wechat.mp.handler;

import java.util.Date;
import java.util.Map;

import org.jeecgframework.web.cgform.common.CgAutoListConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alex.wechat.core.handler.WxHandler;
import com.alex.wechat.mp.config.WxConsts;
import com.alex.wechat.mp.fans.entity.WxFansEntity;
import com.alex.wechat.mp.fans.service.WxFansServiceI;

import me.chanjar.weixin.message.bean.WxXmlMessage;
import me.chanjar.weixin.message.rule.WxMessageHandler;

/**
 * 用户取消关注公众号Handler
 * 
 * @author Debenson
 * @since 0.1
 */
@WxHandler(value = WxConsts.EVT_UNSUBSCRIBE)
public class UnsubscribeHandler implements WxMessageHandler {
  private static final Logger logger = LoggerFactory.getLogger(MassSendFinishHandler.class);

  @Autowired
  private WxFansServiceI fansServiceI;

  @Override
  public String handle(WxXmlMessage wxMessage, Map<String, Object> context) {
    final String openId = wxMessage.getFromUser();
    logger.info("取消关注用户 OPENID: " + openId);

    WxFansEntity fans = fansServiceI.getByOpenId(openId);
    if (fans != null) {
      fans.setSubscribeTime(new Date().getTime());
      fans.setSubscribe(CgAutoListConstant.BOOL_FALSE);
      try {
        fansServiceI.saveOrUpdate(fans);
      } catch (Exception e) {
      }
    }
    return WxConsts.SUCCESS_MSG;
  }

}
